package com.qiaofang.controller;

import com.qiaofang.common.constant.CommonResponseCode;
import com.qiaofang.common.constant.DelFlagEnum;
import com.qiaofang.common.constant.ExceptionEnum;
import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.model.DevPremisesExport;
import com.qiaofang.common.response.CommonResponse;
import com.qiaofang.common.response.SuccessfulResponseFactory;
import com.qiaofang.constant.CompanyTypeEnum;
import com.qiaofang.constant.DepartmentConstant;
import com.qiaofang.constant.PartnerInfoStatusEnum;
import com.qiaofang.dto.*;
import com.qiaofang.entity.PartnerInfo;
import com.qiaofang.request.*;
import com.qiaofang.response.*;
import com.qiaofang.service.MerchantCompanyService;
import com.qiaofang.service.OtherCompanyService;
import com.qiaofang.service.PartnerInfoService;
import com.qiaofang.util.CalculateUtil;
import com.qiaofang.util.Export;
import com.qiaofang.vo.CompanyVO;
import com.qiaofang.vo.DepartmentVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.Get;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = {"商户接口"})
@RequestMapping(value = "/merchantCompany", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public class MerchantCompanyController {

    private static Logger logger = LoggerFactory.getLogger(MerchantCompanyController.class);

    @Autowired
    private MerchantCompanyService merchantCompanyService;

    @Autowired
    private OtherCompanyService otherCompanyService;

    @Autowired
    private PartnerInfoService partnerInfoService;

    @PostMapping(value = "/listCompany")
    @ApiOperation(value = "查询列表")
    public ListCompanyResponse listCompany(@RequestBody ListCompanyRequest request) {
        ListCompanyResponse response = new ListCompanyResponse();
        ListCompanyDTO dto = new ListCompanyDTO();
        dto.setStatus(request.getStatus());
        dto.setType(request.getType());
        dto.setOutsideSwitch(request.getOutsideSwitch());
        dto.setMerchant2(request.getMerchant2());
        dto.setProvince(request.getProvince());
        dto.setCity(request.getCity());
        dto.setZone(request.getZone());
        dto.setCreateTimeStart(request.getCreateTimeStart());
        dto.setCreateTimeEnd(request.getCreateTimeEnd());
        dto.setSearchContent(request.getSearchContent());
        response.setData(merchantCompanyService.listCompany(dto, request.getPage()));
        return response;
    }

    @PostMapping(value = "/listOptionCompany")
    @ApiOperation(value = "公司列表（下拉框）")
    public ListOptionCompanyResponse listOptionCompany() {
        ListOptionCompanyResponse response = new ListOptionCompanyResponse();
        response.setData(merchantCompanyService.listOptionCompany(CompanyTypeEnum.Developer.getType()));
        return response;
    }

    @PostMapping(value = "/addCompany")
    @ApiOperation(value = "新增")
    public CommonResponse addCompany(@RequestBody @Valid AddCompanyRequest request) {
        CompanyDTO dto = new CompanyDTO();
        dto.setCompanyName(request.getCompanyName());
        dto.setCompanyAbbreviation(request.getCompanyAbbreviation());
        dto.setStatus(request.getStatus());
        dto.setCompanyType(request.getCompanyType());
        dto.setProvince(request.getProvince());
        dto.setCity(request.getCity());
        dto.setZone(request.getZone());
        dto.setAddress(request.getAddress());
        dto.setDomain(request.getDomain());
//        PartnerInfoDTO partnerInfoDTO = new PartnerInfoDTO();
//        partnerInfoDTO.setAccountName(request.getAccountName());
//        partnerInfoDTO.setTelephone(request.getTelephone());
//        dto.setPartnerInfo(partnerInfoDTO);
        dto.setIntroduction(request.getIntroduction());
        dto.setWxConfigs(request.getWxConfigs());
        dto.setMerchant2(request.getMerchant2());
        dto.setMerchantCode(request.getMerchantCode());
        dto.setOutsideSwitch(request.getOutsideSwitch());
        dto.setCheckSwitch(request.getCheckSwitch());
        dto.setCheckTemp(request.getCheckTemp());
        dto.setCommissionAuthorizationTime(request.getCommissionAuthorizationTime());
        dto.setCommission(request.getCommission());
//        dto.setWeappMessage(request.getWeappMessage());
        if(request.getWeappMessage()) {
        	dto.setEnableWeappMsg(1);
        }else {
        	dto.setEnableWeappMsg(0);
        }
        dto.setMessageAuthorizationTime(request.getMessageAuthorizationTime());
        dto.setMessage(request.getMessage());
        dto.setDevelopersLoginLogo(request.getDevelopersLoginLogo());
        dto.setDevelopersIndexLogo(request.getDevelopersIndexLogo());
        dto.setAssistantLoginLogo(request.getAssistantLoginLogo());
        dto.setAssistantIndexLogo(request.getAssistantIndexLogo());
        dto.setAssistantExitLogo(request.getAssistantExitLogo());
        dto.setAgencyLoginLogo(request.getAgencyLoginLogo());
        dto.setAgencyIndexLogo(request.getAgencyIndexLogo());
        dto.setH5LoginLogo(request.getH5LoginLogo());
        dto.setAgencyServiceLogo(request.getAgencyServiceLogo());
        dto.setAgencyWeappLogo(request.getAgencyWeappLogo());
        dto.setCheckM2Repeat(request.getCheckM2Repeat());
        merchantCompanyService.addCompany(dto);
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @PostMapping(value = "/updateCompany")
    @ApiOperation(value = "编辑")
    public CommonResponse updateCompany(@RequestBody @Valid UpdateCompanyRequest request) {
        CompanyDTO dto = new CompanyDTO();
        dto.setId(request.getId());
        dto.setCompanyName(request.getCompanyName());
        dto.setCompanyAbbreviation(request.getCompanyAbbreviation());
        dto.setStatus(request.getStatus());
        dto.setCompanyType(request.getCompanyType());
        dto.setProvince(request.getProvince());
        dto.setCity(request.getCity());
        dto.setZone(request.getZone());
        dto.setAddress(request.getAddress());
        dto.setDomain(request.getDomain());
        if(request.getWeappMessage()) {
        	dto.setEnableWeappMsg(1);
        }else {
        	dto.setEnableWeappMsg(0);
        }
//        PartnerInfoDTO partnerInfoDTO = new PartnerInfoDTO();
//        partnerInfoDTO.setId(request.getPartnerInfoId());
//        partnerInfoDTO.setAccountName(request.getAccountName());
//        partnerInfoDTO.setTelephone(request.getTelephone());
//        dto.setPartnerInfo(partnerInfoDTO);
        dto.setIntroduction(request.getIntroduction());
        dto.setWxConfigs(request.getWxConfigs());
        dto.setMerchant2(request.getMerchant2());
        dto.setMerchantCode(request.getMerchantCode());
        dto.setOutsideSwitch(request.getOutsideSwitch());
        dto.setCheckSwitch(request.getCheckSwitch());
        dto.setCheckTemp(request.getCheckTemp());
        dto.setCommissionAuthorizationTime(request.getCommissionAuthorizationTime());
        dto.setCommission(request.getCommission());
        dto.setMessageAuthorizationTime(request.getMessageAuthorizationTime());
        dto.setMessage(request.getMessage());
        dto.setDevelopersLoginLogo(request.getDevelopersLoginLogo());
        dto.setDevelopersIndexLogo(request.getDevelopersIndexLogo());
        dto.setAssistantLoginLogo(request.getAssistantLoginLogo());
        dto.setAssistantIndexLogo(request.getAssistantIndexLogo());
        dto.setAssistantExitLogo(request.getAssistantExitLogo());
        dto.setAgencyLoginLogo(request.getAgencyLoginLogo());
        dto.setAgencyIndexLogo(request.getAgencyIndexLogo());
        dto.setAgencyServiceLogo(request.getAgencyServiceLogo());
        dto.setAgencyWeappLogo(request.getAgencyWeappLogo());
        dto.setH5LoginLogo(request.getH5LoginLogo());
        dto.setCheckM2Repeat(request.getCheckM2Repeat());
        merchantCompanyService.updateCompany(dto);
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @PostMapping(value = "/getCompany")
    @ApiOperation(value = "查询详情")
    public GetCompanyResponse getCompany(@RequestBody @Valid GetCompanyRequest request) {
        GetCompanyResponse response = new GetCompanyResponse();
        response.setData(merchantCompanyService.getCompany(request.getId()));
        return response;
    }

    @PostMapping(value = "/enableCompany")
    @ApiOperation(value = "启用")
    public CommonResponse enableCompany(@RequestBody @Valid EnableCompanyRequest request) {
        merchantCompanyService.enableCompany(request.getId());
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @PostMapping(value = "/disableCompany")
    @ApiOperation(value = "禁用")
    public CommonResponse disableCompany(@RequestBody @Valid DisableCompanyRequest request) {
        merchantCompanyService.disableCompany(request.getId());
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @PostMapping(value = "/deleteCompany")
    @ApiOperation(value = "删除")
    public CommonResponse deleteCompany(@RequestBody @Valid DeleteCompanyRequest request) {
        merchantCompanyService.deleteCompany(request.getId());
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @PostMapping(value = "/batchEnableCompany")
    @ApiOperation(value = "批量启用")
    public CommonResponse batchEnableCompany(@RequestBody @Valid BatchEnableCompanyRequest request) {
        merchantCompanyService.batchEnableCompany(request.getIds());
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @PostMapping(value = "/batchDisableCompany")
    @ApiOperation(value = "批量禁用")
    public CommonResponse batchDisableCompany(@RequestBody @Valid BatchDisableCompanyRequest request) {
        merchantCompanyService.batchDisableCompany(request.getIds());
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @PostMapping(value = "/batchDeleteCompany")
    @ApiOperation(value = "批量删除")
    public CommonResponse batchDeleteCompany(@RequestBody @Valid BatchDeleteCompanyRequest request) {
        merchantCompanyService.batchDeleteCompany(request.getIds());
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @PostMapping(value = "/getDevPremisesExportByPre",produces = "application/json")
    @ApiOperation("按楼盘导出推荐人业务报表")
    public void getDevPremisesExportByPre(DevPremisesExportRequest request, HttpServletResponse response) throws Exception {
        ExportResDto devPremisesExport = merchantCompanyService.getDevPremisesExportByPre(request.getDevCompanyId());
        String expirationDate = devPremisesExport.getDate();
        List<DevPremisesExport> infoList = devPremisesExport.getData();
        // 组装导出数据
        // sheet
        // String[] name = new String[]{"项目客户推荐表", "项目客户转化表"};
        String[] name = new String[] {"统计时间截止至"};
        // 表头
        List<String[]> headerList = new ArrayList<>();
        // 数据
        List<List<Map<String, String>>> list = new ArrayList<>();

        // 项目客户推荐表
        String[] header = new String[] {"楼盘名称", "推荐过的推荐人", "推荐客户", "推荐成功客户", "到访客户", "认筹客户", "认购客户", "签约客户", "签约率"};
        headerList.add(header);

        BigDecimal totalOne = new BigDecimal("0");
        BigDecimal totalTwo = new BigDecimal("0");
        BigDecimal totalThree = new BigDecimal("0");
        BigDecimal totalFour = new BigDecimal("0");
        BigDecimal totalFive = new BigDecimal("0");
        BigDecimal totalSix = new BigDecimal("0");
        BigDecimal totalSeven = new BigDecimal("0");
        String signRate = null;
        List<Map<String, String>> mapList = new ArrayList<>();
        for (int i = 0; i < infoList.size(); i++) {
            DevPremisesExport dpe = infoList.get(i);
            Map<String, String> map = new HashMap<>();
            map.put(header[0] + "_" + i, dpe.getPremisesName());
            String countOne = dpe.getRecommenderCount() + "";
            totalOne = totalOne.add(new BigDecimal(countOne));
            map.put(header[1] + "_" + i, countOne);
            String countTwo = dpe.getCustomerCount() + "";
            totalTwo = totalTwo.add(new BigDecimal(countTwo));
            map.put(header[2] + "_" + i, countTwo);
            String countThree = dpe.getCustomerSuccessCount() + "";
            totalThree = totalThree.add(new BigDecimal(countThree));
            map.put(header[3] + "_" + i, countThree);
            String countFour = dpe.getVisitCustomerCount() + "";
            totalFour = totalFour.add(new BigDecimal(countFour));
            map.put(header[4] + "_" + i, countFour);
            String countFive = dpe.getRaiseCount() + "";
            totalFive = totalFive.add(new BigDecimal(countFive));
            map.put(header[5] + "_" + i, countFive);
            String countSix = dpe.getPurchaseCount() + "";
            totalSix = totalSix.add(new BigDecimal(countSix));
            map.put(header[6] + "_" + i, countSix);
            String countSeven = dpe.getSignCount() + "";
            totalSeven = totalSeven.add(new BigDecimal(countSeven));
            map.put(header[7] + "_" + i, countSeven);

            signRate = CalculateUtil.signRate(countFour,countSeven);
            map.put(header[8] + "_" + i, signRate);
            mapList.add(map);
        }
        Map<String, String> totalMap = new HashMap<>();
        totalMap.put(header[0] + "_" + mapList.size(), "合计");
        totalMap.put(header[1] + "_" + mapList.size(), totalOne.toString());
        totalMap.put(header[2] + "_" + mapList.size(), totalTwo.toString());
        totalMap.put(header[3] + "_" + mapList.size(), totalThree.toString());
        totalMap.put(header[4] + "_" + mapList.size(), totalFour.toString());
        totalMap.put(header[5] + "_" + mapList.size(), totalFive.toString());
        totalMap.put(header[6] + "_" + mapList.size(), totalSix.toString());
        totalMap.put(header[7] + "_" + mapList.size(), totalSeven.toString());


        mapList.add(totalMap);
        list.add(mapList);

        // 项目客户转化表
        String fileName = "推荐人业务报表截止至" + expirationDate;
        name[0] += expirationDate;
        // 组装excel
        Export.exportDevPremisesInfo(list, headerList, name, fileName, response);
    }


    @PostMapping(value = "/getDevPremisesExportByRem",produces = "application/json")
    @ApiOperation("按推荐人导出推荐人业务报表")
    public void getDevPremisesExportByRem(DevPremisesExportRequest request, HttpServletResponse response) throws Exception {
        ExportResDto devPremisesExport = merchantCompanyService.getDevPremisesExportByRem(request.getDevCompanyId());
        String expirationDate = devPremisesExport.getDate();
        List<DevPremisesExport> infoList = devPremisesExport.getData();
        // 组装导出数据
        // sheet
        // String[] name = new String[]{"项目客户推荐表", "项目客户转化表"};
        String[] name = new String[] {"统计时间截止至"};
        // 表头
        List<String[]> headerList = new ArrayList<>();
        // 数据
        List<List<Map<String, String>>> list = new ArrayList<>();

        // 项目客户推荐表
        String[] header = new String[] {"推荐人", "推荐楼盘", "推荐客户", "推荐成功客户", "到访客户", "认筹客户", "认购客户", "签约客户", "签约率"};
        headerList.add(header);

        BigDecimal totalOne = new BigDecimal("0");
        BigDecimal totalTwo = new BigDecimal("0");
        BigDecimal totalThree = new BigDecimal("0");
        BigDecimal totalFour = new BigDecimal("0");
        BigDecimal totalFive = new BigDecimal("0");
        BigDecimal totalSix = new BigDecimal("0");
        BigDecimal totalSeven = new BigDecimal("0");
        String signRate = null;
        List<Map<String, String>> mapList = new ArrayList<>();
        for (int i = 0; i < infoList.size(); i++) {
            DevPremisesExport dpe = infoList.get(i);
            Map<String, String> map = new HashMap<>();
            map.put(header[0] + "_" + i, dpe.getRecommender());
            String countOne = dpe.getPremisesCount() + "";
            totalOne = totalOne.add(new BigDecimal(countOne));
            map.put(header[1] + "_" + i, countOne);
            String countTwo = dpe.getCustomerCount() + "";
            totalTwo = totalTwo.add(new BigDecimal(countTwo));
            map.put(header[2] + "_" + i, countTwo);
            String countThree = dpe.getCustomerSuccessCount() + "";
            totalThree = totalThree.add(new BigDecimal(countThree));
            map.put(header[3] + "_" + i, countThree);
            String countFour = dpe.getVisitCustomerCount() + "";
            totalFour = totalFour.add(new BigDecimal(countFour));
            map.put(header[4] + "_" + i, countFour);
            String countFive = dpe.getRaiseCount() + "";
            totalFive = totalFive.add(new BigDecimal(countFive));
            map.put(header[5] + "_" + i, countFive);
            String countSix = dpe.getPurchaseCount() + "";
            totalSix = totalSix.add(new BigDecimal(countSix));
            map.put(header[6] + "_" + i, countSix);
            String countSeven = dpe.getSignCount() + "";
            totalSeven = totalSeven.add(new BigDecimal(countSeven));
            map.put(header[7] + "_" + i, countSeven);

            signRate = CalculateUtil.signRate(countFour,countSeven);
            map.put(header[8] + "_" + i, signRate);
            mapList.add(map);
        }
        Map<String, String> totalMap = new HashMap<>();
        totalMap.put(header[0] + "_" + mapList.size(), "合计");
        totalMap.put(header[1] + "_" + mapList.size(), totalOne.toString());
        totalMap.put(header[2] + "_" + mapList.size(), totalTwo.toString());
        totalMap.put(header[3] + "_" + mapList.size(), totalThree.toString());
        totalMap.put(header[4] + "_" + mapList.size(), totalFour.toString());
        totalMap.put(header[5] + "_" + mapList.size(), totalFive.toString());
        totalMap.put(header[6] + "_" + mapList.size(), totalSix.toString());
        totalMap.put(header[7] + "_" + mapList.size(), totalSeven.toString());


        mapList.add(totalMap);
        list.add(mapList);

        // 项目客户转化表
        String fileName = "推荐人业务报表截止至" + expirationDate;
        name[0] += expirationDate;
        // 组装excel
        Export.exportDevPremisesInfo(list, headerList, name, fileName, response);
    }

    @PostMapping(value = "/batchBindCompany")
    @ApiOperation(value = "批量绑定V10")
    public CommonResponse batchBindCompany(@RequestBody BatchBindCompanyRequest request) {
        CommonResponse response =new CommonResponse();
        try {
            otherCompanyService.batchAdd(request.getCompanyList());
            response = SuccessfulResponseFactory.getSuccessResponse();
        } catch (Exception e){
            logger.error("batchBindCompany is error: {}",e);
            response.setResponseCode("-1");
            response.setResponseMessage("添加失败！");
        }
        return response;
    }

    @PostMapping(value = "/findOtherCompany")
    @ApiOperation(value = "查询绑定V10的公司")
    public BatchBindCompanyResponse findOtherCompany(@RequestBody @Valid GetCompanyRequest request){
        List<BindCompanyDTO> list = otherCompanyService.selectOtherCompanyList(request.getId());
        BatchBindCompanyResponse response = new BatchBindCompanyResponse();
        response.setData(list);
        return response;
    }

    @PostMapping(value = "/batchUpdateBindCompany")
    @ApiOperation(value = "批量绑定V10")
    public CommonResponse batchUpdateBindCompany(@RequestBody BatchBindCompanyRequest request) {
        CommonResponse response =new CommonResponse();
        try {
            response = otherCompanyService.batchUpdate(request.getCompanyList());;
        } catch (Exception e){
            logger.error("batchUpdateBindCompany is error: {}",e);
            response.setResponseCode("-1");
            response.setResponseMessage("修改失败！");
        }
        return response;
    }

    @PostMapping(value = "/deleteBindCompany")
    @ApiOperation(value = "解除公司绑定")
    public CommonResponse deleteBindCompany(@RequestBody @Valid DeleteCompanyRequest request) {
        otherCompanyService.deleteOtherCompany(request.getId());
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @PostMapping(value = "/buildManger")
    @ApiOperation(value = "创建商户管理员")
    public CommonResponse buildManger(@RequestBody @Valid Long companyId){
        CommonResponse response = new CommonResponse();
        if(companyId == null){
            response.setResponseCode(CommonResponseCode.RC_EXCEPTION_ERROR.getResponseCode());
            response.setResponseMessage(CommonResponseCode.RC_EXCEPTION_ERROR.getResponseMessage());
            return response;
        }
        CompanyVO company = merchantCompanyService.getCompany(companyId);
        if(company == null){
            response.setResponseCode(CommonResponseCode.RC_EXCEPTION_ERROR.getResponseCode());
            response.setResponseMessage("找不到该商户，请查证后访问");
            return response;
        }
        PartnerInfo partnerInfo = new PartnerInfo();
        partnerInfo.setStatus(PartnerInfoStatusEnum.Enable.getNo());
        partnerInfo.setAccountName("manager");
        partnerInfo.setAccountType("0");
        partnerInfo.setHigherId(String.valueOf(company.getId()));
        partnerInfo.setPassword("07c9df7c3840d30aef08fb5c8b3815a7");
        //验证手机号
        partnerInfo.setPhone("18888888888");
        partnerInfo.setIsAdmin("99");
        partnerInfo.setDelFlag(DelFlagEnum.UNDEL.getNo());
        partnerInfo.setDeptId(null);
        partnerInfoService.addPartnerInfo(partnerInfo);
        return SuccessfulResponseFactory.getSuccessResponse();
    }

    @PostMapping(value = "/cleanCompanyCache")
    @ApiOperation(value = "清除整个公司缓存")
    public CommonResponse cleanCompanyCache(@RequestBody @Valid GenericIdRequest request) {
        merchantCompanyService.cleanCompanyCache(request.getId());
        return SuccessfulResponseFactory.getSuccessResponse();
    }
}
